package org.streets.eis.component.model;

import org.apache.wicket.Application;
import org.apache.wicket.Session;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.util.lang.PropertyResolver;
import org.apache.wicket.util.lang.PropertyResolverConverter;
import org.apache.wicket.util.string.Strings;

/**
 * 用做选择时id与text相同的时候，也可通过继承实现自定义Text的选择器
 *
 */
public class ListItemModel extends PropertyModel<ListItem>{

	private static final long serialVersionUID = 1L; 
	
	public ListItemModel(Object modelObject, String expression) {
		super(modelObject, expression);
	}

	@Override
	public ListItem getObject(){
		final String expression = propertyExpression();
		if (Strings.isEmpty(expression)){
			return new ListItem("","");
		}

		final Object target = getTarget();
		if (target != null){
			String id = (String) PropertyResolver.getValue(expression, target);			
			return new ListItem(id,getItemText(id));
		}
		return null;
	}

	@Override
	public void setObject(ListItem object){
		final String expression = propertyExpression();
		if (!Strings.isEmpty(expression)){
			PropertyResolverConverter prc = null;
			prc = new PropertyResolverConverter(Application.get().getConverterLocator(),Session.get().getLocale());
			PropertyResolver.setValue(expression, getTarget(), object.getId(), prc);
		}
	}

	protected String getItemText(String id){
		return id.toString();
	}
}
